package edu.scau.cxq.gp.controller;

import com.alibaba.fastjson.JSONArray;
import edu.scau.cxq.gp.common.annotation.ResponseResult;
import edu.scau.cxq.gp.common.entity.CronEntity;
import edu.scau.cxq.gp.common.entity.MyFile;
import edu.scau.cxq.gp.dto.CronDTO;
import edu.scau.cxq.gp.service.MyFileService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 报表脚本前端控制器
 */
@RestController
@ResponseResult
@RequestMapping("/report-script")
@ConfigurationProperties("file-utils")
@Data
public class ReportScriptController {

    @Autowired
    private MyFileService myFileService;

    // shell 脚本目录
    private String shellScriptDirectory;

    private String logDirectory;

    /**
     *  获取所有的shell脚本
     * @return
     * @throws IOException
     */
    @GetMapping("/getShellScripts")
    private JSONArray getShellScripts() throws IOException {
        List<MyFile> allFile = myFileService.getAllFile(shellScriptDirectory);

        JSONArray jsonArray = new JSONArray();
        jsonArray.addAll(allFile);

        return jsonArray;
    }

    /**
     * 保存shell脚本
     * @param myFile
     * @return
     * @throws UnsupportedEncodingException
     */
    @PostMapping("/saveShellScript")
    private boolean saveShellScript (@RequestBody MyFile myFile) throws UnsupportedEncodingException {
        return myFileService.saveFile(myFile);
    }

    /**
     * 保存cron
     */
    @PostMapping("/saveCron")
    private boolean saveCron (@RequestBody CronDTO cronDTO) {

        return myFileService.saveCron(cronDTO);
    }

    /**
     * 获取对应文件的cron
     */
    @GetMapping("/getCron")
    private CronDTO getCron (@RequestParam(value = "filepath", required = false) String filepath) {

        return myFileService.getCron(filepath);
    }

    /**
     *  获取所有的shell脚本
     * @return
     * @throws IOException
     */
    @GetMapping("/getLogs")
    private JSONArray getLogs() throws IOException {
        List<MyFile> allFile = myFileService.getAllFile(logDirectory);

        JSONArray jsonArray = new JSONArray();
        jsonArray.addAll(allFile);

        return jsonArray;
    }

    /**
     * 删除文件
     */
    @PostMapping("/deleteOne")
    private boolean deleteOne(@RequestBody MyFile myFile) {
        return myFileService.delFile(myFile);
    }
}
